What is the need for virtual functions in C++?
What is the need for virtual functions in C++?
439
07-Jul-2023
Updated on 10-Jul-2023
Aryan Kumar
10-Jul-2023Virtual functions are needed in C++ to allow polymorphism, which is the ability of an object to behave differently depending on its type.
Polymorphism is achieved by making a function virtual. A virtual function is a function that is declared in a base class and can be overridden in a derived class. Overriding a function means providing a different implementation of the function in the derived class.
When a virtual function is called on an object, the compiler will look for the most derived version of the function that is applicable to the object. For example, if a
Derivedclass object calls a virtual function that is also defined in theBaseclass, the compiler will call theDerivedclass version of the function.Virtual functions are used in a variety of situations, such as: